/**
 * @projectName: petJoyHome
 * @author: 小飞
 * @description: TODO
 * @date: 2024/3/1 14:50
 * @version: 1.0
 */
package com.home.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;

public class JwtUtil {
    /**
     * 生成jwt
     * @param secretKey
     * @param ttlMills
     * @param claims
     * @return
     */
    public static String createJWT(String secretKey, long ttlMills, Map<String,Object> claims){
        //设置签名算法
        SignatureAlgorithm signatureAlgorithm =  SignatureAlgorithm.HS256;
        long expMillis = System.currentTimeMillis() + ttlMills;
        Date exp = new Date(expMillis);
        JwtBuilder jwtBuilder = Jwts.builder()
                .setClaims(claims)
                .setIssuer("小飞")
                .signWith(signatureAlgorithm,secretKey.getBytes(StandardCharsets.UTF_8))
                .setExpiration(exp);
        return jwtBuilder.compact();
    }

    /**
     * 解析jwt
     * @param secretKey
     * @param token
     * @return
     */
    public static Claims parseJWT(String secretKey,String token){
        Claims claims = Jwts.parser()
                .setSigningKey(secretKey.getBytes(StandardCharsets.UTF_8))
                .parseClaimsJws(token).getBody();
        return claims;
    }
}
